<template>
  <div>
    <van-sticky>
     <LeadsSearch @updateParentSearchQuery="updateParentSearchQuery"></LeadsSearch>

      <div style="color: #888888;padding: 10px;background-color: #FFFFFF">
        <van-row :gutter="[20, 10]">
          <van-col span="6">
            <span :class="[selectStatusColor]" @click="queryStatus">状态 <van-icon :name="showStatusPopup ? 'arrow-up':'arrow-down'" /></span>
          </van-col>
          <van-col span="8">
            <span :class="[selectDateColor]" @click="queryDate" >{{selectDateLabel}} <van-icon :name="showDatePopup ? 'arrow-up':'arrow-down'" /></span>
          </van-col>
          <van-col span="10" align="end">
            <van-icon :class="[selectQueryColor]" size="20" @click="queryAll" name="filter-o" />
          </van-col>
          <van-col span="12">
            <span>共 {{meta.totalCount}} 位潜客符合条件</span>
          </van-col>

          <!-- 1.TreeSelect 分类选择 -->
          <van-popup v-model:show="showStatusPopup" :close-on-click-overlay="false" position="bottom">
            <div style="padding:30px 10px">
              <van-tree-select
                  v-model:active-id="activeId"
                  v-model:main-active-index="mainActiveIndex"
                  :items="statusArr"
                  @click-item="onClickStatusItem"
              />
              <div style="padding-top: 20px">
                <van-row :gutter="[10]">
                  <van-col span="12">
                    <van-button type="default" style="width:100%" block @click="cancelStatus">清空</van-button>
                  </van-col>
                  <van-col span="12">
                    <van-button type="primary" :disabled="!activeId" style="width:100%" block @click="confirmStatus">确认</van-button>
                  </van-col>
                </van-row>
              </div>
            </div>

          </van-popup>
          <!-- 2.时间 -->
          <van-popup v-model:show="showDatePopup" :close-on-click-overlay="false"  position="bottom" :style="{ 'min-height': '30%' }">
            <div style="padding:30px 10px">
              <CustomDate ref="customDateRef"  @updateParentSelectDataType="updateParentSelectDataType"/>
              <div style="padding-top: 20px">
                <van-row :gutter="[10]">
                  <van-col span="12">
                    <van-button type="default" style="width:100%" block @click="cancelDate">清空</van-button>
                  </van-col>
                  <van-col span="12">
                    <van-button type="primary" :disabled="selectDateType === null" style="width:100%" block @click="confirmDate">确认</van-button>
                  </van-col>
                </van-row>
              </div>
            </div>
          </van-popup>
          <!-- 3.筛选 -->
          <van-popup v-model:show="showQueryPopup" :close-on-click-overlay="false"  position="bottom"  :style="{ height: '100vh', overflow: 'hidden' }">
            <div style="background-color: #f9f9f9;  overflow-y: auto;height: 100%">
              <LeadsQuery ref="queryRef"></LeadsQuery>
              <van-sticky position="bottom">
                <div class="p-2" style="background-color: #ffffff">
                  <van-row :gutter="[10]">
                    <van-col span="12">
                      <van-button type="default" style="width:100%" block @click="cancelQuery">清空</van-button>
                    </van-col>
                    <van-col span="12">
                      <van-button type="primary" style="width:100%" block @click="confirmQuery" :disabled="!queryRef?.isQuery">确认</van-button>
                    </van-col>
                  </van-row>
                </div>
              </van-sticky>
            </div>
          </van-popup>

        </van-row>
      </div>
    </van-sticky>




    <div class="contact-list">
      <van-list
          v-model:loading="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="getDataList"
      >
        <template v-for="contact of dataList" :key="contact.uuid">
          <van-row class="mb-2" @click="showDetail(contact.uuid)">
            <van-col span="4">
              <van-image round width="40" height="40" :src="contact.headimgurl ? contact.headimgurl : generateAvatar(contact.name)" />
            </van-col>
            <van-col span="14">
              <div class="contact-info">
                <div class="contact-name">
                  <span>{{ contact.name }}</span>
                  <van-tag type="primary" class="mr-2">{{contact.leads_phase}}</van-tag>
                  <van-tag type="warning" plain class="mr-2" v-if="contact.leads_status">{{contact.leads_status}}</van-tag>
                </div>
                <div class="contact-company" v-if="contact.company">
                  公司：<span class="company-name">{{ contact.company }}</span>
                </div>
                <div class="contact-source">留资来源：{{ contact.source }}</div>
              </div>
            </van-col>
            <van-col span="6">
              <div class="flex flex-col items-end justify-around min-h-[60px] space-y-8">
                <div class="contact-time">{{ contact.leads_date }}</div>
                <div class="flex items-center space-x-3">
                  <span v-if="contact.work_external_userid && identityType === 'work_userid'" class="iconfont icon-qiyeweixin" @click.stop="workUserProfile(contact.work_external_userid)"></span>
                  <van-icon name="phone-o" class="phone-icon" color="#1989fa" @click.stop="makeCall(contact.mobile)" />
                </div>
              </div>
            </van-col>
          </van-row>
          <van-divider />
        </template>

      </van-list>
    </div>

    <van-sticky :offset-bottom="60" position="bottom">
      <van-button icon="plus" type="primary" class="circle-button" @click="addLead"/>
      <van-popup v-model:show="showAddPopup" position="bottom" closeable close-icon-position="top-left">
        <div class="pt-5 pb-5">
          <h1 class="text-center pb-2">选择潜客添加方式</h1>
          <van-cell @click="manualAdd" title="手动添加潜客" is-link arrow-direction="right" label="描述信息" icon="edit" style="--van-cell-icon-size: 24px;width: 100vw"/>
          <van-uploader :after-read="recognizeCard">
            <van-cell title="识别名片" is-link arrow-direction="right" label="识别名片额度剩余200次" icon="photo-o" style="--van-cell-icon-size: 24px;width: 100vw"/>
          </van-uploader>
        </div>
      </van-popup>

      <!--  添加潜客    -->
      <van-popup v-model:show="showAddLeadsPopup" :close-on-click-overlay="false"  position="bottom"  :style="{ height: '100vh', overflow: 'hidden' }">
        <div style="background-color: #f9f9f9;  overflow-y: auto;height: 100%">
          <LeadsAdd ref="queryRef" :sale_uuid="omniUserUuid" :recognition-data = recognitionData @update:show="updateShowAddLeadsPopup"></LeadsAdd>
        </div>
      </van-popup>

    </van-sticky>

    <Nav></Nav>
  </div>
</template>

<script setup lang="ts">
import {onMounted,computed, reactive, ref, watch} from 'vue'
import {closeToast, showToast, UploaderFileListItem} from 'vant';

import {useRouter,useRoute} from "vue-router";
import { Nav,CustomDate,LeadsQuery,LeadsAdd,LeadsSearch } from '@/views/components/leads';
import {LeadsList, LeadsListResult, StatusList, StatusLeads, CardRecognition, Recognition} from "@/api/leads.ts";
import { Meta } from "@/api/models";
import Compressor from "compressorjs";
import { generateAvatar } from '@/utils/avatar'
import {initWork, openUserProfile} from "@/utils/work";


const route = useRoute();
const router = useRouter();
const customerUuid = route.params.customerUuid;

interface queryParam{
  query: {
    assign_sale_uuid?:string
    leads_status_uuid?:string|object
    leads_remark_uuid?:string|object
    assign_sale_updated_at?:object
    leads_phase?:object
    profile_scoring_level?:object
    action_scoring_level?:object

    name?:object
    mobile?:object
    email?:object
    company?:object
    position?:object
    address?:object
  },
  page:number,
  sort:string,
  perPage:number
}

//const store = useUserStore();
//const assignSaleUuid = computed(() => store.user?.omni_user_uuid as string);
const omniUserUuid = localStorage.getItem('omni_user_uuid') as string;
const identityType = localStorage.getItem('identity_type') as string;
const queryParam = reactive<queryParam>({
  query: {
    assign_sale_uuid:omniUserUuid
  },
  page:1,
  sort:"-assign_sale_updated_at",
  perPage:20
});
const dataList = ref<LeadsListResult[]>([]);
const meta = ref<Meta>({
  totalCount: 0,
  pageCont: 0,
  currentPage: 1,
  perPage: 20
});



const loading = ref(false);
const finished = ref(false);

watch(() => queryParam.query, () => {
  dataList.value = [];
  finished.value = false
  queryParam.page = 1
  getDataList()
}, { deep: true });

const getDataList = async () => {
  if (finished.value) return;
  if(!omniUserUuid){
    finished.value = true;
    return
  }
  try {
    loading.value = true;
    let queryParamClone = {
      ...queryParam,
      query: JSON.stringify(queryParam.query)
    };
    await LeadsList(queryParamClone).then((response) => {
      meta.value = response.data._meta
      const data = response.data.items;
      if (data.length > 0) {
        dataList.value = [...dataList.value, ...data];
        queryParam.page++;
        if(dataList.value.length >= meta.value.totalCount){
          finished.value = true;
        }
      } else {
        finished.value = true;
      }
    });
  } catch (e) {
    console.log(e);
    finished.value = true;
  } finally {
    loading.value = false;
  }
};


// 头部搜索框
type SelectType = "mobile" | "name" | "company" | "position" | "email" | "address";
const updateParentSearchQuery=(selectType:SelectType,searchValue:string)=>{
  //先清空
  delete queryParam.query.name
  delete queryParam.query.mobile
  delete queryParam.query.email
  delete queryParam.query.company
  delete queryParam.query.position
  delete queryParam.query.address

  if(searchValue){
    queryParam.query[selectType] = {
      like:searchValue
    }
  }
}

onMounted(() => {
  initWork()
});

const makeCall = (mobile:string): void => {
  window.location.href = `tel:${mobile}`;
};

const workUserProfile = (userId:string): void => {
  openUserProfile(2,userId)
};


const addLead = ()=>{
  showAddPopup.value = true
}
const showDetail = (uuid:string)=>{
  router.push(`/dist/${customerUuid}/leads/${uuid}`);
}




const queryAll = () => {
  showQueryPopup.value = true
}

const statusArr = ref<StatusLeads[]>([]);
const showStatusPopup = ref(false);
const showDatePopup = ref(false);
const showQueryPopup = ref(false);
const showAddPopup = ref(false);
const showAddLeadsPopup = ref(false);

const mainActiveIndex = ref(0);
const activeId = ref("");


const onClickStatusItem = (item: { text: string, id: string }) => {
  console.log(item.text)
};



const cancelStatus = ()=>{
  activeId.value = ''
  const { leads_status_uuid, leads_remark_uuid, ...rest } = queryParam.query;
  queryParam.query = rest;
  showStatusPopup.value = false
}

const confirmStatus = ()=>{
  if(queryRef.value?.isQuery){
    cancelQuery()
  }
  const { leads_status_uuid, leads_remark_uuid, ...rest } = queryParam.query;
  queryParam.query = rest;
  showStatusPopup.value = false
  if(activeId.value.startsWith("all-")){
    queryParam.query.leads_status_uuid = activeId.value.slice(4)
  }else{
    queryParam.query.leads_remark_uuid = activeId.value
  }
}




const queryStatus=()=>{
  if(statusArr.value.length < 1){
    try {
      StatusList().then((response) => {
        statusArr.value = response.data
      })
    } catch (e) {
      console.log(e);
    } finally {
      showStatusPopup.value = true
    }
  }else{
    showStatusPopup.value = true
  }
}
const queryDate=()=>{
  showDatePopup.value = true
}


const selectDateType = ref<string>("")
const selectDateLabel = ref<string>("时间")
// 1.时间
const customDateRef = ref<InstanceType<typeof CustomDate> | null>(null);


const updateParentSelectDataType = (newValue: string,dateLabel:string) =>{
  selectDateType.value = newValue
  selectDateLabel.value = dateLabel ? dateLabel : "时间"
}










const selectStatusColor = computed(() => {
  return activeId.value ? 'select-color' : '';
});

const selectDateColor = computed(() => {
  return selectDateType.value ? 'select-color' : '';
});
const selectQueryColor = computed(() => {
  return queryRef.value?.isQuery ? 'select-color' : '';
});

const confirmDate = ()=>{
  if(queryRef.value?.isQuery){
    cancelQuery()
  }
  if (customDateRef.value && 'triggerConfirm' in customDateRef.value) {
    queryParam.query.assign_sale_updated_at = (customDateRef.value as any).triggerConfirm()
  }
  showDatePopup.value = false
}
const cancelDate = ()=>{
  if (customDateRef.value && 'triggerCancel' in customDateRef.value) {
    (customDateRef.value as any).triggerCancel();
  }
  delete queryParam.query.assign_sale_updated_at
  showDatePopup.value = false
}

//筛选
const queryRef = ref<InstanceType<typeof LeadsQuery> | null>(null);
const cancelQuery = ()=>{
  clearDateAndStatus()
  if (queryRef.value && 'cancelQuery' in queryRef.value) {
    (queryRef.value as any).cancelQuery();
  }
  queryParam.query = {
    assign_sale_uuid:omniUserUuid
  }
  showQueryPopup.value = false
}
const confirmQuery = ()=>{
  clearDateAndStatus()
  queryParam.query = {}
  if (queryRef.value && 'confirmQuery' in queryRef.value) {
    queryParam.query = (queryRef.value as any).confirmQuery()
  }
  showQueryPopup.value = false
}

const clearDateAndStatus = () => {
  if(selectDateType.value){
    cancelDate()
  }
  if(activeId.value){
    cancelStatus()
  }
}



const manualAdd = () => {
  showAddPopup.value = false
  showAddLeadsPopup.value = true
}

// Function to handle file input and compression
async function recognizeCard(file: UploaderFileListItem | UploaderFileListItem[]) {
  if (Array.isArray(file)) {

  }else{
    try {
      if ((file.file as File).size > 1024 * 1024) {
        // Show loading toast
        showToast({
          type: 'loading',
          message: '处理图片...',
          forbidClick: true,
          duration: 0,
        });

        const base64String = await compressImageToBase64(file.file as File, {
          quality: 0.6,
          maxWidth: 800,
          maxHeight: 800,
        });

        console.log('压缩后 Base64:', base64String);
        closeToast();
        processFile(<string>base64String);
      } else {
        console.log("没有压缩：")
        processFile(<string>file.content);
      }
    } catch (error) {
      console.error('Error compressing image:', error);
      closeToast();
      showToast('压缩失败，请重试');
    }
  }
}


// Function to compress an image and get a Base64 string
function compressImageToBase64(file: File, options: Compressor.Options = {}): Promise<string | ArrayBuffer | null> {
  return new Promise((resolve, reject) => {
    new Compressor(file, {
      ...options,
      success(result) {
        const reader = new FileReader();
        reader.onload = () => {
          resolve(reader.result); // Resolves with the Base64 string
        };
        reader.onerror = error => {
          reject(error);
        };
        reader.readAsDataURL(result); // Convert Blob to Base64
      },
      error(error) {
        reject(error);
      },
    });
  });
}




// 处理文件的方法
const processFile = (imageBase64:string) => {
  recognition({
    ImageBase64: imageBase64
  });
};
const recognitionData = ref<Recognition|null>(null)
const recognition = async (data:object)=>{
  try {
    await CardRecognition(data).then((response) => {
      if (response.code === 0) {
        recognitionData.value = response.data
        showAddPopup.value = false
        showAddLeadsPopup.value = true
      }
    })
  } catch (e) {
    console.log(e);
  } finally {
    
  }
}

const updateShowAddLeadsPopup = (reload:boolean) => {
  showAddLeadsPopup.value = false
  if(reload){
    dataList.value = [];
    finished.value = false
    queryParam.page = 1
    getDataList()
  }
}


</script>

<style scoped>

.contact-list {
  padding: 10px 10px 60px 10px;
}


.contact-info {
  flex: 1;
  font-size: 18px; /* 设置整体字体大小 */
}

.contact-name {
  display: flex;
  align-items: center;
  font-size: 16px; /* 设置姓名字体大小 */
  margin-bottom: 10px;
}

.contact-name span {
  font-weight: bold;
  margin-right: 8px;
}

.contact-tag {
  font-size: 10px; /* 设置标签字体大小 */
  padding: 2px 4px; /* 设置标签内边距 */
  height: auto;
  line-height: 12px; /* 设置标签行高 */
}

.contact-company {
  color: #000;
  font-size: 12px;
  margin-bottom: 8px;
}

.company-name {
  color: #3b8cff;
}

.contact-source {
  color: #888;
  margin-top: 4px;
  font-size: 12px; /* 设置留资来源字体大小 */
}


.contact-time {
  color: #888;
  font-size: 12px; /* 设置时间字体大小 */
}

.phone-icon {
  font-size: 24px; /* 设置电话图标大小 */
}

.no-more {
  text-align: center;
  color: #888;
  padding: 10px 0;
  font-size: 12px; /* 设置“没有更多了”字体大小 */
}


.circle-button {
  width: 50px;  /* 设置按钮的宽度 */
  height: 50px; /* 设置按钮的高度 */
  border-radius: 50%; /* 使按钮变成圆形 */
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0; /* 去除默认的内边距 */
  font-size: 24px; /* 设置按钮图标大小 */
  position: fixed; /* 固定位置 */
  left: 20px; /* 距离左侧40px */
  bottom: 80px; /* 距离底部100px，与van-sticky的offset-bottom匹配 */
  z-index: 1000; /* 保证在顶层 */
}

.select-color {
  color: #3b8cff;
}
.iconfont {
  font-size: 18px;
  color: #1989fa;
}
</style>
